<?php

use app\modules\Admin\models\pickgoodscardModel;
use Illuminate\Database\Capsule\Manager as DB;

#[提货卡管理]
class PickgoodscardController extends AcommonController
{
    public function init() {
        $this->model = (new pickgoodscardModel());
        $this->table = 'pickgoods_card';
        $this->primaryKey = 'id';
        parent::init();
    }

    #[提货卡列表]
    public function indexAction($returnData = false)
    {
        if($this->isPost()){
            if(!empty($this->postData['pickgoodscardkeywords'])){
                $this->model = $this->model->where(function($query) {
                    $query->where('name', 'like', "%{$this->postData['pickgoodscardkeywords']}%")
                        ->orWhere('id', $this->postData['pickgoodscardkeywords']);
                });
            }
            $this->model = $this->model->where(function ($query){
                $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
            });
            $this->hiddens = ['rules', 'description', 'updated_at', 'goods_ids'];
            $pickgoodscard_rows =  parent::indexAction(true);
            if($pickgoodscard_rows['total'] && count($pickgoodscard_rows['rows'])){
                foreach ($pickgoodscard_rows['rows'] as &$row){
                    $goods_list = [];
                    if(!empty($row['goods_ids_array'])){
                        foreach ($row['goods_ids_array'] as $goods_id){
                            $goodsModel = goodsModel::query()->where('id', $goods_id)->select(['id', 'title', 'image'])->first();
                            if($goodsModel){
                                $goods_list[] =  $goodsModel->makeHidden(['dispatch_type_arr', 'parent_category_id'])->toArray();
                            }
                        }
                    }
                    $row['goods_list'] = $goods_list;
                }
            }
            json($pickgoodscard_rows);
        }else{
            $this->_view->display( strtolower($this->controller) . '/index.html');
        }
    }

    #[新增提货卡]
    public function addAction()
    {
        if($this->isPost()) {
            do {
                $rows = $this->postData;
                if(empty($rows['amount'])){
                    $result = [
                        'ret' => 2,
                        'msg' => '提货卡面值只能是大于0的数值！',
                    ];
                    break;
                }
                $rows['gettime_start'] = $rows['gettime_start']??null;
                $rows['gettime_end'] = $rows['gettime_end']??null;
                $rows['validtime_start'] = $rows['validtime_start']??null;
                $rows['validtime_end'] = $rows['validtime_end']??null;
                $rows['goods_ids'] = implode(',', $rows['goods_ids']);
                $rows['created_at'] = timestamp();
                unset($rows[$this->primaryKey], $rows['updated_at']);
                $this->cleanColumn($rows);
                try{
                    DB::transaction(function () use ($rows) {
                        if(is_object($this->model)){
                            $query = $this->model;
                        }else{
                            $query = is_string($this->model) ? (new $this->model) : DB::table($this->table);
                        }
                        $query->insert($rows);
                    });
                    $result = [
                        'ret' => 0,
                        'msg' => '恭喜，新增提货卡成功! ^_^',
                    ];
                }catch (Exception $e){
                    $result = [
                        'ret' => 1,
                        'msg' => '抱歉，新增提货卡失败。',
                    ];
                } finally {
                    unset($rows);
                }
            } while (FALSE);
            json($result);
        }else{
            $this->_view->assign('pickgoodscard_id', 0);
            $this->_view->display( strtolower($this->controller) . '/add.html');
        }
    }

    #[编辑提货卡]
    public function editAction()
    {
        if (!$this->get('id')){
            ret(1, '参数出错！');
        }
        if($this->isPost()){
            $params = $this->postData;
            if($params['mode'] == 'submit'){
                do {
                    $pickgoodscard_id = $this->get('id');
                    $rows = $this->postData;
                    $rows['gettime_start'] = $rows['gettime_start']?:null;
                    $rows['gettime_end'] = $rows['gettime_end']?:null;
                    $rows['validtime_start'] = $rows['validtime_start']?:null;
                    $rows['validtime_end'] = $rows['validtime_end']?:null;
                    $rows['goods_ids'] = implode(',', $rows['goods_ids']);
                    $rows['updated_at'] = timestamp();
                    unset($rows[$this->primaryKey]);
                    $this->cleanColumn($rows);
                    try{
                        DB::transaction(function () use ($rows, $pickgoodscard_id) {
                            pickgoodscardModel::query()->where('id', $pickgoodscard_id)->update($rows);
                        });
                        $result = [
                            'ret' => 0,
                            'msg' => '恭喜，提货卡编辑成功! ^_^',
                        ];
                    }catch (Exception $e){
                        $result = [
                            'ret' => 3,
                            'msg' => '抱歉，编辑提货卡失败。',
                        ];
                    } finally {
                        unset($rows);
                    }
                } while (FALSE);
                json($result);
            }else{
                $resInfo = [];
                $info = pickgoodscardModel::query()->where('id', $params['id'])->first();
                if($info){
                    $goods_ids = explode(',', $info->goods_ids);
                    asort($goods_ids, 1);
                    $goods_ids = array_merge([], $goods_ids);
                    $resInfo['info']['name'] = $info->name;
                    $resInfo['info']['amount'] = $info->amount;
                    $resInfo['info']['valid_day'] = $info->valid_day;
                    $resInfo['info']['description'] = $info->description;
                    $resInfo['info']['type'] = $info->type;
                    $resInfo['info']['goods_ids'] = $goods_ids;
                    $resInfo['info']['startend_time'][0] = $info->gettime_start;
                    $resInfo['info']['startend_time'][1] = $info->gettime_end;
                    $resInfo['info']['valid_time'][0] = $info->validtime_start;
                    $resInfo['info']['valid_time'][1] = $info->validtime_end;
                    $resInfo['goodsList'] = goodsModel::query()->whereIn('id', $goods_ids)->select(['id', 'title', 'image', 'is_sku', 'price', 'created_at'])->orderBy('id', 'ASC')->get();
                    ret(0,'success', $resInfo);
                }else{
                    ret(2, '提货卡不存在！');
                }
            }
        }else{
            $this->_view->assign('pickgoodscard_id', $this->get('id'));
            $this->_view->display( strtolower($this->controller) . '/add.html');
        }
    }

    #[删除提货卡]
    public function deleteAction()
    {
        $id = $this->get($this->primaryKey, 0);
        if (empty($id)) {
            ret(2, '参数为空');
        }
        $delModel = $this->model->where('id', $id)->where(function ($query){
            $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
        })->first();
        if(!$delModel){
            ret(4, '提货卡不存在');
        }
        if(\app\modules\Admin\models\goodspackageModel::query()->where('card_info', 'like', "%\"id\":\"{$id}\"%")->exists()){
            ret(8,'提货卡已经绑定套餐商品，无法删除');
        }
        if(\app\modules\Admin\models\memberpickgoodscardModel::query()->where('card_id', $id)->where('money', '>', 0)->whereDate('expire', '>=', timestamp())->where(function ($query){
            $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
        })->count('id')){
            ret(9, '此提货卡已发放并且在有效期中已经被使用，无法删除');
        }
        $delModel->deleted_at = timestamp();
        if($delModel->save()){
            $memberCard = \app\modules\Admin\models\memberpickgoodscardModel::query()->where('card_id', $id)->where(function ($query){
                $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
            })->get();
            if($memberCard){
                foreach ($memberCard as $item){
                    $item->deleted_at = timestamp();
                    if($item->save()){
                        \app\modules\Admin\service\Memberpickgoodscardlog::addLog([
                            'member_pickgoods_card_id' => $item->id,
                            'event' => 'recover',
                            'event_id' => $id,
                            'before' => $item->money,
                            'money' => 0-$item->money,
                            'after' => 0,
                            'remark'     => '管理员删除提货卡，全部回收！',
                            'oper_type'  => 'admin',
                            'oper_id'    => $this->auth->user_id,
                        ]);
                    }
                }
                unset($item);
            }
            unset($memberCard);
            unset($delModel);
            unset($id);
            ret(0, '提货卡删除成功！');
        }else{
            ret(1, '提货卡删除失败');
        }

    }

    #[获取商品列表]
    public function getgoodsAction()
    {
        if($this->isPost()){
            $query = goodsModel::query()->where('status', 'up')->where('is_package', 0)->where(function ($query){
                $query->whereNull('deleted_at')->orWhereDate('deleted_at', '<=', '0000-00-00');
            });
            $keywords = $this->postData['keywords'];
            if (!empty($keywords)) {
                $query = $query->Where(function ($orwQuery) use($keywords){
                    $orwQuery->where('title', 'like',  "%{$keywords}%")
                        ->orWhere('id', $keywords);
                });
            }
            $minprice = $this->get('minprice', 0);
            if(!empty($minprice)){
                $query = $query->where('price', '>=', $minprice);
            }
            $maxprice = $this->get('maxprice', 0);
            if(!empty($maxprice)){
                $query = $query->where('price', '<=', $maxprice);
            }
            $total = $query->count();
            $query = $query->orderBy('id', 'DESC');
            $page = $this->get('page')?:1;
            $limit = $this->get('rows', 10);
            $offset = ($page - 1) * $limit;
            $query = $query->offset($offset)->limit($limit);
            $rows = $query->select(['id', 'image', 'title', 'is_sku', 'price', 'created_at'])
                ->get()->makeHidden(['dispatch_type_arr', 'parent_category_id']);
            if($rows){
                foreach ($rows as &$row){
                    $row->skuInfo = [];
                    $row->stock =  goodsskupriceModel::select(DB::raw('sum(stock) as allstock'))->where('goods_id', $row->id)->value('allstock');
                }
            }
            json(['total' => $total, 'rows' => $rows]);
        }else{
            $this->_view->display( strtolower($this->controller) . '/getgoodslist.html');
        }
    }
}